#coding=utf-8

from time import sleep
import datetime,os
#environ needed for standalone script using django model
import stutils 
stutils.set_django_environ()
###
from djstock.shstock.models import *
#from webscrapper.rtprice import get_rtprice
from config import DIRNAME
import scraper

LIVEPRICEDIR = DIRNAME + '/live/liveprice'
def liveprice2db(e, rp, mm5d):
    lp = LivePrice(exday=e)
    
    lp.time = rp[1]
    lp.price = rp[2]
    lp.change = rp[3]
    lp.volume = rp[4]
    lp.amount =  rp[5]
    
    for i in range(5):
        sn = str(5-i)
        attr_p = "s%s_price"%sn
        attr_v = "s%s_volume"%sn
        
        p,v = mm5d[i]
        
        setattr(lp, attr_p, p)
        setattr(lp, attr_v, v)
    
    for i in range(5):
        sn = str(i+1)
        attr_p = "b%s_price"%sn
        attr_v = "b%s_volume"%sn
        
        p,v = mm5d[i+5]
        
        setattr(lp, attr_p, p)
        setattr(lp, attr_v, v)
    
    lp.save()   
   
'''    
code = '600028'
td = datetime.date.today().isoformat()
fn = '%s/%s_%s.csv'%(LIVEPRICEDIR , code, td)

s = Share.objects.get(code=code)
ts = s.ts

e = s.exday_set.latest('date')
if e.date.isoformat() != td:
    e = create_today(code)

if os.path.exists(fn):
    f = open(fn, 'a')
else:
    f = open(fn, 'w')
    head = '时间,价格,成交量,换手率'


    f.write(head)
    f.write('\n')
    f.flush()

pre_volume = 0
while True:
    rp, mm5d = get_rtprice(code)    
    
    t = rp[1]
    p = rp[2]
    v = rp[4]
    
    if pre_volume != v:
        
        hsl = float(v) * 100 /ts
        hsl = str( float2dec(hsl, 4) )
        
        s = ','.join([t,p,v,hsl])
        f.write(s)
        f.write('\n')
        f.flush()
        
        pre_volume = v
        
        #put data to db
        liveprice2db(e,rp,mm5d)
        sleep(0.2)
        
    else:
        print 'data have not changed right now.'
'''

for s in Share.objects.all():
    try:
        rp, mm5d = scraper.get_rtprice(s.code)
    except scraper.NoLivepriceNowError,e:
        print e
        continue
    
    td = datetime.date.today().isoformat()
    e = s.exday_set.latest('date')
    if e.date.isoformat() != td:
        e = create_today(s.code)    
    liveprice2db(e,rp,mm5d)
    
    print s